Request = require 'request'
Async = require 'async'
_ = require 'underscore'
Fs = require 'fs'
Logger = require('log4js').getLogger()
# Canvas = require 'canvas'


downloadTotal = 0

class ImageHandle
  constructor : (options) ->
    defaults = 
      downloadLimit : 5
    @opts = _.extend defaults, options
  downloadImages : (imageList) ->
    self = @
    opts = self.opts
    if !_.isArray imageList
      return self
    downloadLimit = opts.downloadLimit
    Async.forEachLimit imageList, downloadLimit, (imgSrc, cbf) ->
      requestOpts = 
        url : imgSrc
        encoding : null
      Request requestOpts, (err, res, data) ->
        if err
          Logger.error err
        else
          console.log "isBuffer#{Buffer.isBuffer(data)}"
          # img = new Image
          # img.src = data
          # console.log "width:#{img.width}, height:#{img.height}"
          Fs.writeFile "/Users/vicanso/workspace/my_node/tmp/#{downloadTotal}.jpg", data, 'binary'
          downloadTotal++
        cbf()
    , () ->
      console.log 'finished'

module.exports = ImageHandle